package cn.gailvlun.gll.presentation.login.viewmodel

import android.app.Activity
import android.app.Dialog
import android.databinding.BaseObservable
import android.databinding.Bindable
import android.databinding.ObservableField
import cn.gailvlun.gll.BR
import cn.gailvlun.gll.BuildConfig
import cn.gailvlun.gll.databinding.ActivityCompleteProfileBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.base.GetAvatarRes
import cn.gailvlun.gll.net.base.Profile
import cn.gailvlun.gll.net.base.invite.ConfirmInviteReq
import cn.gailvlun.gll.net.base.invite.ConfirmInviteRes
import cn.gailvlun.gll.net.base.profile.AddProfileReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.login.SelectHeaderActivity
import cn.gailvlun.gll.presentation.login.adapter.GenderType
import cn.gailvlun.gll.util.*
import com.bigkoo.pickerview.OptionsPickerView
import com.bigkoo.pickerview.TimePickerView
import com.blankj.utilcode.util.KeyboardUtils
import java.util.*


class CompleteProfileViewModel(val activity: BaseActivity, private val mBinding: ActivityCompleteProfileBinding) : BaseObservable() {


    private lateinit var pd: Dialog

    val nickname = ObservableField<String>("")
    var item: GetAvatarRes = GetAvatarRes()

    
    @Bindable
    fun getAvatarUrl(): String? {
        return item.trust_url
    }

    fun onClickHeader() {
        SelectHeaderActivity.openActivityForResult(activity)
                .subscribe { activityResult ->
                    if (activityResult.resultCode() == Activity.RESULT_OK) {
                        val getAvatarRes = activityResult.data().getSerializableExtra("data") as GetAvatarRes

                        item.file_name = getAvatarRes.file_name
                        item.trust_url = getAvatarRes.trust_url
                        notifyPropertyChanged(BR.avatarUrl)
                    }
                }
    }

    
    fun getInvite() {
        if (BuildConfig.DEBUG) {
            HttpMethods.getInviteService()
                    .addInvite()
                    .compose(RxUtil.applyScheduler())
                    .subscribe(object : HttpSubscriber<ConfirmInviteRes>() {
                        override fun onSuccess(response: ConfirmInviteRes) {
                            mBinding.cetInvite.setText(response.key)
                        }

                        override fun onFailure(errMsg: String, response: ConfirmInviteRes?, code: Int) {

                        }
                    })
        }
    }

    fun onAddProfile() {
        val nickName = mBinding.cetNick.text.toString().trim()
        if (IsEmpty.string(nickName)) {
            ToastUtil.showShort("请填写昵称")
            return
        }

        if (IsEmpty.string(mBinding.cetInvite.text.toString().trim())) {
            ToastUtil.showShort("请填写邀请码")
            return
        }
        pd = DialogUtil.showIndeterminate(activity)

        val addProfileReq = AddProfileReq()

        addProfileReq.avatar = item?.file_name
        addProfileReq.name = nickName
        addProfileReq.birthday=mBinding.tvBirthday.text.toString().trim()
        addProfileReq.city=mBinding.tvCity.text.toString().trim()
        addProfileReq.isGender= mBinding.genderType?.isMale!!

        
        
        HttpMethods.getProfileService()
                .modifyProfile(addProfileReq)
                .compose(RxUtil.applyScheduler())
                .compose<Profile>(activity.bindToLifecycle())
                .subscribe(object : HttpSubscriber<Profile>() {
                    override fun onSuccess(response: Profile) {
                        val nowProfile = ProfileUtil.getProfile()
                        response.token = nowProfile!!.token
                        response.refresh_token = nowProfile.refresh_token

                        ProfileUtil.modify(response)

                        onConfirmInvite()
                    }

                    override fun onFailure(errMsg: String, response: Profile?, code: Int) {
                        if (pd.isShowing) {
                            pd.dismiss()
                        }
                        DialogUtil.showError(activity, errMsg)
                    }
                })
    }

    private fun onConfirmInvite() {
        
        HttpMethods.getInviteService()
                .confirmInvite(ConfirmInviteReq(mBinding.cetInvite.text.toString()))
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<ConfirmInviteRes>() {
                    override fun onSuccess(response: ConfirmInviteRes) {
                        if (pd.isShowing) {
                            pd.dismiss()
                        }

                        val nowProfile = ProfileUtil.getProfile()
                        LoginUtil.complete(activity, nowProfile)
                    }

                    override fun onFailure(errMsg: String, response: ConfirmInviteRes?, code: Int) {
                        if (pd.isShowing) {
                            pd.dismiss()
                        }
                        DialogUtil.showError(activity, errMsg)
                    }
                })
    }

    fun onGender(genderType: GenderType?) {
        KeyboardUtils.hideSoftInput(activity)
        val genderList = Arrays.asList(*GenderType.values())
        val pickerView = OptionsPickerView.Builder(activity,
                OptionsPickerView.OnOptionsSelectListener { options1, options2, options3, v ->
                    val selectGender = genderList[options1]
                    mBinding.setGenderType(selectGender)
                }).build()
        pickerView.setPicker(genderList)
        if (genderType != null) {
            pickerView.setSelectOptions(genderType.ordinal)
        }
        pickerView.show()
    }

    fun onBirthday(selectedDate: Calendar?) {
        KeyboardUtils.hideSoftInput(activity)
        val pvTime = TimePickerView.Builder(activity, TimePickerView.OnTimeSelectListener { date, v -> mBinding.setBirthday(DateUtil.toCalendar(date)) })
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("年", "月", "日", null, null, null)
                .build()
        if (selectedDate == null) {
            pvTime.setDate(Calendar.getInstance())
        } else {
            pvTime.setDate(selectedDate)
        }
        pvTime.show()
    }


}